import moment from 'moment';
import React, { Fragment } from 'react';
import nzh from 'nzh/cn';
import { parse, stringify } from 'qs';
import single_error from './../images/single_error.png';
import single_one from './../images/single_one.png';
import single_two from './../images/single_two.png';
import single_three from './../images/sigle_three.png';
import single_four from './../images/single_four.png';
import ppt from './../images/ppt.png';
import word from './../images/word.png';
import xls from './../images/xls.png';
import image from './../images/image.png';
import unknow from './../images/unknow.png';
import zip from './../images/zip.png';
import txt from './../images/txt.png';
import pdf from './../images/pdf.png';
import exe from './../images/exe.png';
import issue_1 from './../images/issue-1.png';
import issue1 from './../images/issue1.png';
import issue2 from './../images/issue2.png';
import issue3 from './../images/issue3.png';
import issue4 from './../images/issue4.png';
import issue5 from './../images/issue5.png';
import issue6 from './../images/issue6.png';
import {message, Badge, Tooltip, TreeSelect, Switch, Icon, Tag} from 'antd';

const TreeNode = TreeSelect.TreeNode;

export function fixedZero(val) {
  return val * 1 < 10 ? `0${val}` : val;
}

export function getTimeDistance(type) {
  const now = new Date();
  const oneDay = 1000 * 60 * 60 * 24;

  if (type === 'today') {
    now.setHours(0);
    now.setMinutes(0);
    now.setSeconds(0);
    return [moment(now), moment(now.getTime() + (oneDay - 1000))];
  }

  if (type === 'week') {
    let day = now.getDay();
    now.setHours(0);
    now.setMinutes(0);
    now.setSeconds(0);

    if (day === 0) {
      day = 6;
    } else {
      day -= 1;
    }

    const beginTime = now.getTime() - day * oneDay;

    return [moment(beginTime), moment(beginTime + (7 * oneDay - 1000))];
  }

  if (type === 'month') {
    const year = now.getFullYear();
    const month = now.getMonth();
    const nextDate = moment(now).add(1, 'months');
    const nextYear = nextDate.year();
    const nextMonth = nextDate.month();

    return [
      moment(`${year}-${fixedZero(month + 1)}-01 00:00:00`),
      moment(moment(`${nextYear}-${fixedZero(nextMonth + 1)}-01 00:00:00`).valueOf() - 1000),
    ];
  }

  const year = now.getFullYear();
  return [moment(`${year}-01-01 00:00:00`), moment(`${year}-12-31 23:59:59`)];
}

export function todayLastSecond() {
  let todayYear = (new Date()).getFullYear();
  let todayMonth = (new Date()).getMonth();
  let todayDay = (new Date()).getDate();
  return moment(todayYear + '-' + (parseInt(todayMonth) + 1) + '-' + todayDay + ' 23:59:59', 'YYYY-MM-DD HH:mm:ss').format('YYYY-MM-DD HH:mm:ss');
}
export function getLastDay(year,month) {
  var new_year = year;    //取当前的年份
  var new_month = month++;//取下一个月的第一天，方便计算（最后一天不固定）
  if(month>12) {
    new_month -=12;        //月份减
    new_year++;            //年份增
  }
  var new_date = new Date(new_year,new_month,1);                //取当年当月中的第一天
  return (new Date(new_date.getTime()-1000*60*60*24)).getDate();//获取当月最后一天日期
}
export function getPlainNode(nodeList, parentPath = '') {
  const arr = [];
  nodeList.forEach(node => {
    const item = node;
    item.path = `${parentPath}/${item.path || ''}`.replace(/\/+/g, '/');
    item.exact = true;
    if (item.children && !item.component) {
      arr.push(...getPlainNode(item.children, item.path));
    } else {
      if (item.children && item.component) {
        item.exact = false;
      }
      arr.push(item);
    }
  });
  return arr;
}

export function digitUppercase(n) {
  return nzh.toMoney(n);
}

function getRelation(str1, str2) {
  if (str1 === str2) {
    console.warn('Two path are equal!'); // eslint-disable-line
  }
  const arr1 = str1.split('/');
  const arr2 = str2.split('/');
  if (arr2.every((item, index) => item === arr1[index])) {
    return 1;
  }
  if (arr1.every((item, index) => item === arr2[index])) {
    return 2;
  }
  return 3;
}

function getRenderArr(routes) {
  let renderArr = [];
  renderArr.push(routes[0]);
  for (let i = 1; i < routes.length; i += 1) {
    // 去重
    renderArr = renderArr.filter(item => getRelation(item, routes[i]) !== 1);
    // 是否包含
    const isAdd = renderArr.every(item => getRelation(item, routes[i]) === 3);
    if (isAdd) {
      renderArr.push(routes[i]);
    }
  }
  return renderArr;
}

/**
 * Get router routing configuration
 * { path:{name,...param}}=>Array<{name,path ...param}>
 * @param {string} path
 * @param {routerData} routerData
 */
export function getRoutes(path, routerData) {
  let routes = Object.keys(routerData).filter(
    routePath => routePath.indexOf(path) === 0 && routePath !== path,
  );
  // Replace path to '' eg. path='user' /user/name => name
  routes = routes.map(item => item.replace(path, ''));
  // Get the route to be rendered to remove the deep rendering
  const renderArr = getRenderArr(routes);
  // Conversion and stitching parameters
  const renderRoutes = renderArr.map(item => {
    const exact = !routes.some(route => route !== item && getRelation(route, item) === 1);
    return {
      exact,
      ...routerData[`${path}${item}`],
      key: `${path}${item}`,
      path: `${path}${item}`,
    };
  });
  return renderRoutes;
}

export function getPageQuery() {
  return parse(window.location.href.split('?')[1]);
}

export function getQueryPath(path = '', query = {}) {
  const search = stringify(query);
  if (search.length) {
    return `${path}?${search}`;
  }
  return path;
}

/* eslint no-useless-escape:0 */
const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;

export function isUrl(path) {
  return reg.test(path);
}

export function formatWan(val) {
  const v = val * 1;
  if (!v || Number.isNaN(v)) return '';

  let result = val;
  if (val > 10000) {
    result = Math.floor(val / 10000);
    result = (
      <span>
        {result}
        <span
          styles={{
            position: 'relative',
            top: -2,
            fontSize: 14,
            fontStyle: 'normal',
            lineHeight: 20,
            marginLeft: 2,
          }}
        >
          万
        </span>
      </span>
    );
  }
  return result;
}

const removeLoginStorage = (company_code) => {
  sessionStorage.removeItem('username');
  sessionStorage.removeItem('token');
  sessionStorage.removeItem('permissions');
  sessionStorage.clear();
  // localStorage.clear()
  // localStorage.removeItem('username');
  // localStorage.removeItem('token');
};
exports.removeLoginStorage = removeLoginStorage;

export function converErrorCodeToMsg(error) {
  console.log('error', error.toString());
  if (error.toString() === 'Error: Request failed with status code 500') {
    message.error('出现未知错误,请联系开发人员', 3);
    return false;
  }
  if (error.toString() === 'Error: Network Error') {
    message.error('网络错误', 3);
    return false;
  }
  if (error.response.status === 401) {
    // message.error(messageJson['token fail']);
    setTimeout(function() {
      removeLoginStorage();
      window.location.href = '/user/login';
    }, 1000);
  } else if (!error.response.data.errors) {
    message.error(error.response.data.message);
  } else if (error.response.status === 422) {
    let first;
    for (first in error.response.data.errors) break;
    message.error(`${error.response.data.errors[first][0]}`);
  } else {
    message.error('未知错误');
  }
}

export function converDevicesInfo(data) {

  let sensorskey = [];
  let topicskey = [];
  for (let i in data) {
    let splitSensorsKey = i.split('#');
    let splitTopicsKey = i.split('&');
    let sensorsLen = splitSensorsKey.length;
    let topicsLen = splitTopicsKey.length;
    if (sensorsLen >= 2) {
      if (sensorskey.indexOf(splitSensorsKey[1]) < 0) {
        sensorskey.push(splitSensorsKey[1]);
      }
    }
    if (topicsLen >= 2) {
      if (topicskey.indexOf(splitTopicsKey[1]) < 0) {
        topicskey.push(splitTopicsKey[1]);
      }
    }
  }

  let sensorsArr = [];
  let topicsArr = [];
  for (let i = 0; i < sensorskey.length; i++) {
    sensorsArr.push({
      number: data[`number#${sensorskey[i]}`],
      alias: data[`alias#${sensorskey[i]}`],
      data_type: data[`data_type#${sensorskey[i]}`],
      remark: data[`remark#${sensorskey[i]}`],
    });
  }
  for (let j = 0; j < topicskey.length; j++) {
    topicsArr.push({
      name: data[`name&${topicskey[j]}`],
      allow_publish: data[`allow_publish&${topicskey[j]}`],
      allow_subscribe: data[`allow_subscribe&${topicskey[j]}`],
    });
  }

  data.sensorsArr = sensorsArr;
  data.topicsArr = topicsArr;
  return data;
}

export function isAntdPro() {
  return window.location.hostname === 'preview.pro.ant.design';
}

export function ellipsis(val, len = 150) {
  if (val !== undefined) {
    return (
      <Tooltip title={val}>
       <span className="table-ellipsis" data-tip={val} style={{
         maxWidth: `${len - 12}px`,
       }}>{val}</span>
      </Tooltip>

    );
  } else {
    return '';
  }

}

exports.ellipsis = ellipsis;


function renderIndex(meta, page, index) {
  const parseIndex = meta ? String((meta.per_page * (page - 1)) + (index + 1)) : 0;
  return (
    <span title={parseIndex}>
                {parseIndex.length > 4 ? parseIndex.substring(0, 3) + '...' : parseIndex}
            </span>
  );
}

exports.renderIndex = renderIndex;


export function toTree(data) {
  console.log('data', data);
  data.forEach(function(item) {
    delete item.children;
  });

  // 将数据存储为 以 id 为 KEY 的 map 索引数据列
  var map = {};
  data.forEach(function(item) {
    map[item.id] = item;
  });
//        console.log(map);
  var val = [];
  data.forEach(function(item) {
    // 以当前遍历项，的pid,去map对象中找到索引的id
    var parent = map[item.parent_id];
    // 好绕啊，如果找到索引，那么说明此项不在顶级当中,那么需要把此项添加到，他对应的父级中
    if (parent) {
      (parent.children || (parent.children = [])).push(item);
    } else {
      //如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中，作为顶级
      val.push(item);
    }
  });
  return val;
}

export function deleteTreeChildren(data) {
  console.log('data', data);
  if(data){
    data.forEach(function(item) {
      if (item.children && item.children.length === 0) {
        delete item.children;
      } else {
        deleteTreeChildren(item.children);
      }
    });
  }

  return data;
}

export function download(url) {
  let iframe = document.createElement('a');
  // iframe.style.display = 'none'
  // iframe.style.width = '150px'
  // iframe.style.height = '150px'
  iframe.href = url;
  // iframe.text = url
  iframe.onload = function() {
    console.log('onload');
    document.body.removeChild(iframe);
  };
  document.body.appendChild(iframe);
  iframe.click();
}

export function afterCloseModal(modalClass) {
  console.log('afterCloseModal');
  try {
    let modal_wrap = document.getElementsByClassName(
      'ant-modal-wrap',
    );
    for (let i = 0; i < modal_wrap.length; i++) {
      modal_wrap[i].style.transform =
        'translate(0px, 0px)';
    }
    // document.querySelector('.'+modalClass).parentElement.style.transform =
    //   "translate(0px, 0px)";
  } catch (e) {
    console.log('e', e);
  }
}

export function DescriptionItem({ title, content }) {
  return <div
    style={{
      fontSize: 14,
      lineHeight: '22px',
      marginBottom: 7,
      color: 'rgba(0,0,0,0.65)',
    }}
  >
    <p
      style={{
        marginRight: 8,
        display: 'inline-block',
        color: 'rgba(0,0,0,0.95)',
      }}
    >
      {title} :
    </p>
    {content}
  </div>;
}

export function transilateBinary(num, Bits = 16) {
  var resArry = [];
  var xresArry = [];
  let i = 0;
  for (; num > 0;) {
    resArry.push(num % 2);
    num = parseInt(num / 2);
    i++;
  }
  for (let j = i - 1; j >= 0; j--)
    xresArry.push(resArry[j]);
  if (Bits < xresArry.length) {
    console.log('位数小于二进制位数');
  }
  if (Bits) {
    for (let r = xresArry.length; r < Bits; r++) {
      xresArry.unshift(0);
    }
  }
  return xresArry.join().replace(/,/g, '');
}

export function string2Obj(str) {
  let arr = str.split('');
  let obj = {
    key: uuid(),
  };
  for (let i = 0; i < arr.length; i++) {
    obj[i] = arr[i];
  }
  return obj;
}

export function arr2obj(arr) {
  let obj = {
    key: uuid(),
  };
  for (let i = 0; i < arr.length; i++) {
    obj[arr[i].sensor_index] = arr[i].value;
  }
  return obj;

}

export function arrTrans(num, arr) { // 一维数组转换为二维数组
  const iconsArr = []; // 声明数组
  arr.forEach((item, index) => {
    const page = Math.floor(index / num); // 计算该元素为第几个素组内
    if (!iconsArr[page]) { // 判断是否存在
      iconsArr[page] = [];
    }
    iconsArr[page].push(item);
  });
  return iconsArr;
}

export function renderValueStatus(val) {
  let status = 'success';
  let explain = '';
  switch (val) {
    case -4:
      status = 'error';
      explain = '错报';
      break;
    case -3:
      status = 'error';
      explain = '抄表失败';
      break;
    case -2:
      status = 'warning';
      explain = '漏报';
      break;
    case -1:
      status = 'warning';
      explain = '未上报';
      break;
    default:
      status = 'success';
      explain = '正常';
  }
  return (
    <p>
      <Badge status={status}/>{explain}
    </p>
  );
}

export function renderSignalIntensity(val) {
  if (val !== '') {
    val = Number(val);
  }

  if (val == 99 || val == '') {
    return <span><img style={{ width: '30px', height: '20px', position: 'relative', top: '-2px' }} src={single_error}
                      alt=""/> {val}</span>;
  }
  if (0 <= val && val <= 10) {
    return <span><img style={{ width: '30px', height: '20px', position: 'relative', top: '-2px' }} src={single_one}
                      alt=""/> {val}</span>;
  } else if (10 < val && val <= 20) {
    return <span><img style={{ width: '30px', height: '20px', position: 'relative', top: '-2px' }} src={single_two}
                      alt=""/> {val}</span>;
  } else if (20 < val && val <= 30) {
    return <span><img style={{ width: '30px', height: '20px', position: 'relative', top: '-2px' }} src={single_three}
                      alt=""/> {val}</span>;
  } else if (30 < val && val < 32) {
    return <span><img style={{ width: '30px', height: '20px', position: 'relative', top: '-2px' }} src={single_four}
                      alt=""/> {val}</span>;
  } else {
    return <span><img style={{ width: '30px', height: '20px', position: 'relative', top: '-2px' }} src={single_error}
                      alt=""/> {val}</span>;
  }
}
export function renderMeterStatus(val) {
  const parseST1=parseInt(val.substr(2,2),16).toString(2).padStart(8, '0')
  const b0=parseST1.substr(7,1)
  const b1=parseST1.substr(6,1)
  const b2=parseST1.substr(5,1)
  const b3=parseST1.substr(4,1)
  const b4=parseST1.substr(3,1)
  let alarmTags=[]
  if(b0==='1'){
    alarmTags.push('压力报警')
  }
  if(b1==='1'){
    alarmTags.push('温度报警')
  }
  if(b2==='1'){
    alarmTags.push('持续流量报警')
  }
  if(b3==='1'){
    alarmTags.push('倾斜报警')
  }
  if(b4==='1'){
    alarmTags.push('有流量')
  }
  if(alarmTags.length>0){
    return alarmTags.map((item,index)=>{
      if((index+1)===alarmTags.length){
        return <Fragment key={index}>
          <Tag   style={{marginRight:'5px',borderRightWidth:(index+1)!==alarmTags.length?0:'1px'}} color={'red'}>{item}</Tag>
        </Fragment>
      }else{
        return <Fragment key={index}>
          <Tag   style={{marginRight:'5px',borderRightWidth:(index+1)!==alarmTags.length?0:'1px'}} color={'red'}>{item}</Tag>
        </Fragment>
      }

    })
  }else{
    return  <Tag color={'blue'}>正常</Tag>
  }

}
export function renderValveOpen(val) {
  let type = '';
  let color = '';
  let text = '';
  switch (val) {
    case -1:
      type = 'close-circle', color = '#eb2f96', text = '关';
      return <p className={'table-error table-status'}>关闭</p>;
      break;
    case 1:
      type = 'check-circle', color = '#52c41a', text = '开';
      return <p className={'table-success table-status'}>开启</p>;
      break;
    case 2:
      type = 'close-circle', color = '#fe5810', text = '未上报';
      break;
    case 3:
      type = 'close-circle', color = '#fe1b2e', text = '异常';
      break;
    default:
      type = 'close-circle', color = '#eb2f96', text = '异常';
      break;
  }
  return <Fragment> <Icon type={type} theme="twoTone" className="table-icon" twoToneColor={color}/>{text}</Fragment>;
}

export function renderConStatus(val) {
  let type = '';
  let color = '';
  let text = '';
  switch (val) {
    case -1:
      return <p className={'table-error table-status'}>离线</p>;
      break;
    case 1:
      return <p className={'table-success table-status'}>在线</p>;
      break;
    case 2:
      type = 'close-circle', color = '#fe5810', text = '未上报';
      break;
    case 3:
      type = 'close-circle', color = '#fe1b2e', text = '异常';
      break;
    default:
      type = 'close-circle', color = '#eb2f96', text = '异常';
      break;
  }
  return <Fragment> <Icon type={type} theme="twoTone" className="table-icon" twoToneColor={color}/>{text}</Fragment>;
}

export function renderTreeNodes(data) { // 一维数组转换为二维数组
  return data.map((item) => {
    if (item.children) {
      return (
        <TreeNode value={`${item.id}$${item.name}`} title={item.name} key={item.id}>
          {renderTreeNodes(item.children)}
        </TreeNode>
      );
    }
    return <TreeNode value={item.id} title={item.name} key={item.id}/>;
  });
}

function formateObjToParamStr(paramObj) {
  const sdata = [];
  for (let attr in paramObj) {
    if(attr==='user_ids'){
      for(let i=0;i<paramObj[attr].length;i++){
          sdata.push(`${attr}[]=${paramObj[attr][i]}`);
      }

    }else{
        sdata.push(`${attr}=${paramObj[attr]}`);
    }

  }
  return sdata.join('&');
}

exports.formateObjToParamStr = formateObjToParamStr;

export function printUtils(data) {
  const printParams = {
    hdbh: data.id,
    bjbh: data.account.meter_number,
    yhxm: data.account.name,
    yhdh: data.account.mobile,
    yhdz: data.account.address,
    bqds: data.billing_value,
    sqds: '',
    cbrq: data.billing_date,
    jfqsrq: '',
    jfjsrq: '',
    jfrq: data.payment_date,
    ysl: data.purchased_water_volume,
    sqye: data.account.last_balance,
    bqye: data.account.current_balance,
    skfs: data.billing_type === 1 ? '预存' : '后付',
    fymc: data.account.price_nature.name,
    jcsf_dj: data.account.price_nature.level_one_price,
    jcsf_je: '',
    wsclf_dj: data.account.price_nature.level_one_sewage_price,
    wsclf_je: '',
    ssje: data.amount,
    syy: data.branch_telephone,
    czy: data.operator_name,
  };
  const paramsStr = formateObjToParamStr(printParams);
  window.open(`http://182.61.46.172:19562/print3.html?${paramsStr}`);

}

export function printUtilsLevel(data) {
  const printParams = {
    hdbh: data.id,
    bjbh: data.account.meter_number,
    yhxm: data.account.name,
    yhdh: data.account.mobile,
    yhdz: data.account.address,
    bqds: data.billing_value,
    sqds: '',
    cbrq: data.billing_date,
    jfqsrq: '',
    jfjsrq: '',
    jfrq: data.payment_date,
    sqye: data.account.last_balance,
    bqye: data.account.current_balance,
    skfs: data.billing_type === 1 ? '预存' : '后付',
    fymc: data.account.price_nature.name,
    jcsf_je: '',
    jcsf_dj1: data.account.price_nature.level_one_price,
    jcsf_dj2: data.account.price_nature.level_two_price,
    jcsf_dj3: data.account.price_nature.level_three_price,
    wsclf_dj1: data.account.price_nature.level_one_sewage_price,
    wsclf_dj2: data.account.price_nature.level_two_sewage_price,
    wsclf_dj3: data.account.price_nature.level_three_sewage_price,
    ysl: '',
    wsclf_je: '',
    ssje: data.amount,
    syy: data.branch_telephone,
    czy: data.operator_name,
  };
  const paramsStr = formateObjToParamStr(printParams);
  window.open(`http://106.13.201.3:19562/print4.html?${paramsStr}`);

}

export function popoverPrice(price_nature) {
  return <Fragment>
    <p>阶梯数量: {price_nature.level}</p>
    <p><span style={{ marginRight: '5px' }}>一阶价格: <span
      className={Boolean(Number(price_nature.level_one_price)) ? 'green' : ''}>{price_nature.level_one_price}</span></span>
      <span>一阶污水处理费: <span
        className={Boolean(Number(price_nature.level_one_sewage_price)) ? 'green' : ''}>{price_nature.level_one_sewage_price}</span></span>
    </p>
    <p><span style={{ marginRight: '5px' }}>二阶价格: <span
      className={Boolean(Number(price_nature.level_two_price)) ? 'green' : ''}>{price_nature.level_two_price}</span></span>
      <span>二阶污水处理费: <span
        className={Boolean(Number(price_nature.level_two_sewage_price)) ? 'green' : ''}>{price_nature.level_two_sewage_price}</span></span>
    </p>
    <p><span style={{ marginRight: '5px' }}>三阶价格: <span
      className={Boolean(Number(price_nature.level_three_price)) ? 'green' : ''}>{price_nature.level_three_price}</span></span>
      <span>三阶污水处理费: <span
        className={Boolean(Number(price_nature.level_three_sewage_price)) ? 'green' : ''}>{price_nature.level_three_sewage_price}</span></span>
    </p>
    <p><span style={{ marginRight: '5px' }}>一阶水量: <span
      className={Boolean(Number(price_nature.level_one_consumption)) ? 'green' : ''}>{price_nature.level_one_consumption}</span></span>
      <span>二阶水量: <span
        className={Boolean(Number(price_nature.level_two_consumption)) ? 'green' : ''}>{price_nature.level_two_consumption}</span></span>
    </p>
  </Fragment>;
}

export function popoverBling(price_nature) {
  return <Fragment>
    <p><span style={{ marginRight: '5px' }}>一阶扣费: <span
      className={Boolean(Number(price_nature.level_one_fee)) ? 'green' : ''}>{price_nature.level_one_fee}</span></span>
      <span>一阶污水扣费: <span
        className={Boolean(Number(price_nature.level_one_sewage_fee)) ? 'green' : ''}>{price_nature.level_one_sewage_fee}</span></span>
    </p>
    <p><span style={{ marginRight: '5px' }}>二阶扣费: <span
      className={Boolean(Number(price_nature.level_two_fee)) ? 'green' : ''}>{price_nature.level_two_fee}</span></span>
      <span>二阶污水扣费: <span
        className={Boolean(Number(price_nature.level_two_sewage_fee)) ? 'green' : ''}>{price_nature.level_two_sewage_fee}</span></span>
    </p>
    <p><span style={{ marginRight: '5px' }}>二阶扣费: <span
      className={Boolean(Number(price_nature.level_three_fee)) ? 'green' : ''}>{price_nature.level_three_fee}</span></span>
      <span>二阶污水扣费: <span
        className={Boolean(Number(price_nature.level_three_sewage_fee)) ? 'green' : ''}>{price_nature.level_three_sewage_fee}</span></span>
    </p>
  </Fragment>;
}

export function getFileType(fileName) {
  // 后缀获取
  let suffix = '';
  // 获取类型结果
  let result = '';
  try {
    const flieArr = fileName.split('.');
    suffix = flieArr[flieArr.length - 1];
  } catch (err) {
    suffix = '';
  }
  // fileName无后缀返回 false
  if (!suffix) {
    return false;
  }
  suffix = suffix.toLocaleLowerCase();
  // 图片格式
  const imglist = ['png', 'jpg', 'jpeg', 'bmp', 'gif'];
  // 进行图片匹配
  result = imglist.find(item => item === suffix);
  if (result) {
    return image;
  }
  // 匹配txt
  const txtlist = ['txt'];
  result = txtlist.find(item => item === suffix);
  if (result) {
    return txt;
  }
  // 匹配 excel
  const excelist = ['xls', 'xlsx'];
  result = excelist.find(item => item === suffix);
  if (result) {
    return xls;
  }
  // 匹配 word
  const wordlist = ['doc', 'docx'];
  result = wordlist.find(item => item === suffix);
  if (result) {
    return word;
  }
  // 匹配 pdf
  const pdflist = ['pdf'];
  result = pdflist.find(item => item === suffix);
  if (result) {
    return pdf;
  }
  // 匹配 ppt
  const pptlist = ['ppt', 'pptx'];
  result = pptlist.find(item => item === suffix);
  if (result) {
    return ppt;
  }
  // 匹配 压缩文件
  const ziplist = ['zip', 'rar'];
  result = ziplist.find(item => item === suffix);
  if (result) {
    return zip;
  }
  // 匹配 EXE
  const exelist = ['exe'];
  result = exelist.find(item => item === suffix);
  if (result) {
    return exe;
  }
  // 其他 文件类型
  return unknow;
}

export function timeStamp(second_time) {

  let time = '0d ' + '00:00:' + fixedZero(parseInt(second_time));
  if (parseInt(second_time) > 59) {

    let second = fixedZero(parseInt(second_time) % 60);
    let min = fixedZero(parseInt(second_time / 60));
    time = '0d ' + '00:' + min + ':' + second;

    if (min > 59) {
      min = fixedZero(parseInt(second_time / 60) % 60);
      let hour = fixedZero(parseInt(parseInt(second_time / 60) / 60));
      time = '0d ' + hour + ':' + min + ':' + second;

      if (hour > 23) {
        hour = fixedZero(parseInt(parseInt(second_time / 60) / 60) % 24);
        let day = parseInt(parseInt(parseInt(second_time / 60) / 60) / 24);
        time = day + 'd ' + hour + ':' + min + ':' + second;
      }
    }


  }

  return time;
}

export function leaveStatue(value) {
  switch (value) {
    case -1:
      return <p className={'table-error table-status'} style={{ textAlign: 'center' }}>已取消</p>;
    case 1:
      return <p className={'table-warm table-status'} style={{ textAlign: 'center' }}>未提交</p>;
    case 2:
      return <p className={'table-process0 table-status'} style={{ textAlign: 'center' }}>等待审批</p>;
    case 3:
      return <p className={'table-error table-status'} style={{ textAlign: 'center' }}>审批不通过</p>;
    case 4:
      return <p className={'table-process table-status'} style={{ textAlign: 'center' }}>等待复审</p>;
    case 5:
      return <p className={'table-error table-status'} style={{ textAlign: 'center' }}>复审不通过</p>;
    case 6:
      return <p className={'table-success table-status'} style={{ textAlign: 'center' }}>复审通过</p>;
    default :
      return '';
  }
}

export function leaveStatueImg(value) {
  switch (value) {
    case -1:
      return <div style={{position:'absolute',right:'10px',top:'69px',opacity:'0.6'}}><img style={{width:'120px'}} src={issue_1} alt=""/></div>;
    case 1:
      return <div style={{position:'absolute',right:'10px',top:'69px',opacity:'0.6'}}><img style={{width:'120px'}} src={issue1} alt=""/></div>;
    case 2:
      return <div style={{position:'absolute',right:'10px',top:'69px',opacity:'0.6'}}><img style={{width:'120px'}} src={issue2} alt=""/></div>;
    case 3:
      return <div style={{position:'absolute',right:'10px',top:'69px',opacity:'0.6'}}><img style={{width:'120px'}} src={issue3} alt=""/></div>;
    case 4:
      return  <div style={{position:'absolute',right:'10px',top:'69px',opacity:'0.6'}}><img style={{width:'120px'}} src={issue4} alt=""/></div>;
    case 5:
      return  <div style={{position:'absolute',right:'10px',top:'69px',opacity:'0.6'}}><img style={{width:'120px'}} src={issue5} alt=""/></div>;
    case 6:
      return  <div style={{position:'absolute',right:'10px',top:'69px',opacity:'0.6'}}><img style={{width:'120px'}} src={issue6} alt=""/></div>;
    default :
      return '';
  }
}


function getLatFromTree (data,arr=[]) {
  data.map(item => {
    if (item.children&&item.children.length>0) {
      arr.push(item)
      return getLatFromTree(item.children,arr);
    }
    arr.push(item)
  });
  return arr
}
exports.getLatFromTree = getLatFromTree;


export function convertCurrency(money) {
  //汉字的数字
  var cnNums = new Array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');
  //基本单位
  var cnIntRadice = new Array('', '拾', '佰', '仟');
  //对应整数部分扩展单位
  var cnIntUnits = new Array('', '万', '亿', '兆');
  //对应小数部分单位
  var cnDecUnits = new Array('角', '分', '毫', '厘');
  //整数金额时后面跟的字符
  var cnInteger = '整';
  //整型完以后的单位
  var cnIntLast = '元';
  //最大处理的数字
  var maxNum = 999999999999999.9999;
  //金额整数部分
  var integerNum;
  //金额小数部分
  var decimalNum;
  //输出的中文金额字符串
  var chineseStr = '';
  //分离金额后用的数组，预定义
  var parts;
  if (money == '') {
    return '';
  }
  money = parseFloat(money);
  if (money >= maxNum) {
    //超出最大处理数字
    return '';
  }
  if (money == 0) {
    chineseStr = cnNums[0] + cnIntLast + cnInteger;
    return chineseStr;
  }
  //转换为字符串
  money = money.toString();
  if (money.indexOf('.') == -1) {
    integerNum = money;
    decimalNum = '';
  } else {
    parts = money.split('.');
    integerNum = parts[0];
    decimalNum = parts[1].substr(0, 4);
  }
  //获取整型部分转换
  if (parseInt(integerNum, 10) > 0) {
    var zeroCount = 0;
    var IntLen = integerNum.length;
    for (var i = 0; i < IntLen; i++) {
      var n = integerNum.substr(i, 1);
      var p = IntLen - i - 1;
      var q = p / 4;
      var m = p % 4;
      if (n == '0') {
        zeroCount++;
      } else {
        if (zeroCount > 0) {
          chineseStr += cnNums[0];
        }
        //归零
        zeroCount = 0;
        chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
      }
      if (m == 0 && zeroCount < 4) {
        chineseStr += cnIntUnits[q];
      }
    }
    chineseStr += cnIntLast;
  }
  //小数部分
  if (decimalNum != '') {
    var decLen = decimalNum.length;
    for (var i = 0; i < decLen; i++) {
      var n = decimalNum.substr(i, 1);
      if (n != '0') {
        chineseStr += cnNums[Number(n)] + cnDecUnits[i];
      }
    }
  }
  if (chineseStr == '') {
    chineseStr += cnNums[0] + cnIntLast + cnInteger;
  } else if (decimalNum == '') {
    chineseStr += cnInteger;
  }
  return chineseStr;
}
